package com.quectel.sdk.zlm.common;

import com.fasterxml.jackson.core.type.TypeReference;
import com.quectel.sdk.zlm.ZlmMediaKitBaseClient;
import com.quectel.sdk.zlm.basemodel.vo.AddFFmpegSourceResp;
import com.quectel.sdk.zlm.basemodel.vo.SetServerConfigResp;
import com.quectel.sdk.zlm.basemodel.vo.StreamAddressAssembleResp;
import com.quectel.sdk.zlm.constant.ZlmMediaKitConstants;
import com.quectel.util.common.URLUtils;
import org.apache.commons.codec.binary.Hex;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 在这里编写说明
 *
 * @author: rananxin
 * @email: ryan.ran@quectel.com
 * @date: 2023-01-13 16:54:00
 */
public class ZlmClient extends ZlmMediaKitBaseClient {

    /**
     * 服务配置下发，配置参数暂时未给出，详情见zlm
     *
     * @param params
     * @return
     */
    public SetServerConfigResp sendConfig(Map<String, Object> params) {
        return requester.post("/index/api/setServerConfig", params, new TypeReference<SetServerConfigResp>() {
        });
    }

    /**
     * 添加源
     *
     * @param key             播放唯一key
     * @param originSourceUrl
     * @return
     */
    public AddFFmpegSourceResp addFFmpegSource(String key, String originSourceUrl) {
        Map<String, Object> params = new HashMap<>();
        params.put("src_url", originSourceUrl);
        params.put("dst_url", String.format("rtmp://127.0.0.1:1935/%s/%s", ZlmMediaKitConstants.DEFAULT_APP, key));
        params.put("timeout_ms", "10000");
        params.put("enable_hls", "0");
        params.put("enable_mp4", "0");

        return requester.post("index/api/addFFmpegSource", params, new TypeReference<AddFFmpegSourceResp>() {
        });
    }

    /**
     * 组装参数
     *
     * @param key
     * @param originalUrl
     * @return
     */
    public StreamAddressAssembleResp streamAddressAssemble(String key, String originalUrl) {

        String originalUrlConverted = Hex.encodeHexString(originalUrl.getBytes(StandardCharsets.UTF_8));

        StreamAddressAssembleResp streamAddressAssembleResp = new StreamAddressAssembleResp();
        streamAddressAssembleResp.setHlsUrl(String.format("%s%s/%s/hls.m3u8?%s", requester.getUrl(), ZlmMediaKitConstants.DEFAULT_APP, key, originalUrlConverted));
        streamAddressAssembleResp.setRtspUrl(String.format("rtsp://%s/%s/%s?%s", URLUtils.getHost(requester.getUrl()), ZlmMediaKitConstants.DEFAULT_APP, key, originalUrlConverted));
        streamAddressAssembleResp.setRtmpUrl(String.format("rtmp://%s/%s/%s?%s", URLUtils.getHost(requester.getUrl()), ZlmMediaKitConstants.DEFAULT_APP, key, originalUrlConverted));
        streamAddressAssembleResp.setHttpFlvUrl(String.format("%s%s/%s/live.flv?%s", requester.getUrl(), ZlmMediaKitConstants.DEFAULT_APP, key, originalUrlConverted));
        return streamAddressAssembleResp;
    }
}
